package com.dmw.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmw.reggie.common.R;
import com.dmw.reggie.dto.SetmealDto;
import com.dmw.reggie.entity.Category;
import com.dmw.reggie.entity.Setmeal;
import com.dmw.reggie.entity.SetmealDish;
import com.dmw.reggie.service.CategoryService;
import com.dmw.reggie.service.SetmealDishService;
import com.dmw.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("setmeal")
public class SetmealController {

    @Resource
    private SetmealService setmealService;

    @Resource
    private SetmealDishService setmealDishService;

    @Resource
    private CategoryService categoryService;

    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @Transactional
    public R save(@RequestBody SetmealDto setmealDto){
        // 将套餐数据保存到套餐表中
        setmealService.save(setmealDto);

        // 获取套餐id
        System.out.println(setmealDto.getId());
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getName, setmealDto.getName());
        Setmeal setmeal = setmealService.getOne(queryWrapper);
        Long setmealId = setmeal.getId();

        // 将数据保存到套餐菜品关联表
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        // 填充 setmealId 字段
        setmealDishes.forEach(i -> {
            i.setSetmealId(setmealId);
        });
        setmealDishService.saveBatch(setmealDishes);

        return R.success(null);
    }

    @GetMapping("/page")
    public R<Page<SetmealDto>> page(Long page, Long pageSize, String name){
        // 构造分页构造器
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>(page, pageSize);

        // 构造条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name), Setmeal::getName, name);

        // 分页查询
        setmealService.page(pageInfo, queryWrapper);

        // 拷贝
        BeanUtils.copyProperties(pageInfo, setmealDtoPage, "records");

        List<Setmeal> setmealRecords = pageInfo.getRecords();
        List<SetmealDto> setmealDtoRecords = new ArrayList<>();

        setmealRecords.forEach(i -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(i, setmealDto);
            Category category = categoryService.getById(i.getCategoryId());
            setmealDto.setCategoryName(category.getName());
            setmealDtoRecords.add(setmealDto);
        });
        setmealDtoPage.setRecords(setmealDtoRecords);

        return R.success(setmealDtoPage);
    }


    /**
     * 根据 id 批量删除除套餐，对于售卖中的套餐需要先停售再删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R deleteById(@RequestParam List<Long> ids){


        // 批量删除（重写，包括删除关联表的数据）
        setmealService.removeByIds(ids);
        return R.success(null);
    }

    /**
     * 停售或起售套餐
     * @param status 0 停售 1 起售
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable("status") Integer status, @RequestParam String ids){
        // 切割出 id
        String[] split = ids.split(",");
        List<String> strings = Arrays.asList(split);

        // 构造条件构造器
        LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Setmeal::getStatus, status)
                .in(Setmeal::getId, strings);

        setmealService.update(updateWrapper);
        return R.success(null);
    }

    /**
     * 根据 id 查询套餐信息，包括菜品数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id){
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);

        return R.success(setmealDto);
    }

    @PutMapping
    public R update(@RequestBody SetmealDto setmealDto){
        setmealService.updateWithDish(setmealDto);
        return R.success(null);
    }

    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getCategoryId, setmeal.getCategoryId())
                .eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        List<Setmeal> list = setmealService.list(queryWrapper);

        return R.success(list);
    }
}
